<template>
  <el-dialog
    model-value="dialogVisible"
    :title="dialogTitle"
    width="60%"
    @close="handleClose"
  >
    <el-form :model="form" label-width="120px" ref="formRef" :rules="rules">
      <el-form-item label="岗位名称" prop="jobName">
        <el-input v-model="form.jobName" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleConfirm">确认</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup>
import { ref, watch } from 'vue'
import { addJob, editJob } from '@/api/job'
import { ElMessage } from 'element-plus'
const emits = defineEmits(['update:modelValue', 'initList'])
const formRef = ref(null)
const form = ref({
  jobName: ''
})

const props = defineProps({
  dialogVisible: {
    type: Boolean,
    default: false,
    required: false
  },
  dialogTitle: {
    type: String,
    default: '',
    required: true
  },
  dialogTableVal: {
    type: Object,
    // default: {} 此处会报错 因为vue规定，对象或数组默认值必须从一个工厂函数获取
    default: function () {
      return {}
    }
  }
})

watch(
  () => props.dialogTableVal,
  () => {
    form.value = props.dialogTableVal
  },
  { deep: true, immediate: true }
)

const handleConfirm = () => {
  formRef.value.validate(async (valid) => {
    if (valid) {
      props.dialogTitle === '添加岗位'
        ? await addJob(form.value)
        : await editJob(form.value)
      ElMessage({
        message: '成功',
        type: 'success'
      })
      emits('initList')
      handleClose()
    } else {
      ElMessage({
        message: '提交失败!!',
        type: 'warning'
      })
      return false
    }
  })
}

const rules = ref({
  jobName: [
    {
      required: true,
      message: '请填写岗位名称',
      trigger: 'blur'
    }
  ]
})

const handleClose = () => {
  // 父组件 v-model 没有指定参数名，则默认是 modelValue
  emits('update:modelValue', false)
}
</script>

<style lang="scss" scoped></style>
